package at.ac.tuwien.ewa.g70.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import at.ac.tuwien.ewa.g70.api.CardManager;

public class MemoryServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
		HttpSession sess = req.getSession(true);
		
		CardManager manager = (CardManager) sess.getAttribute("manager");
		if (manager == null) {
			manager = new CardManager();
			manager.init(CardManager.getDefaultCards(), 4, 4);
			sess.setAttribute("manager", manager);
		}
		
		String uncover = req.getParameter("uncover");
		if (uncover != null && uncover.matches("^(\\d+),(\\d+)$")) {
			String[] idx = uncover.split(",");
			manager.uncover(Integer.valueOf(idx[0]), Integer.valueOf(idx[1]));
		}
		
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/table.jsp");
        dispatcher.forward(req, res);
	}
}
